//
//  HMOAuthViewController.swift
//  swift-新浪微博0
//
//  Created by 赵玉忠 on 16/8/30.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

 let WB_APPKEY = "1284202627"
 let WB_SECRET = "d5db472a093661827d5460866fd552b8"
 let WB_REDIRECT_URI = "http://www.itcast.cn"
class HMOAuthViewController: UIViewController,UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    private func setupUI() {
        view.backgroundColor = UIColor.white
        title = "新浪微博-登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
        
        // 添加控件
        self.view.addSubview(webView)
        
        // 添加约束
        webView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRECT_URI)"
        // 加载指定的登录页面
        // 1. 初始化一个url
        let url = URL(string: urlString)!
        // 2. 通过url初始化一个请求
        let reqeust = URLRequest(url: url)
        // 3. 加载该请求
        webView.loadRequest(reqeust)
    }
    
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    // MARK: - 自动填充功能
        @objc private func autoFill() {
            // 去执行js代码
            let jsString = "document.getElementById('userId').value = '18301166921';document.getElementById('passwd').value = '18301166921';"
            webView.stringByEvaluatingJavaScript(from: jsString)
        }
    
    
    
    // MARK: - UIWebViewDelegate
    // shouldStartLoadWith是否应该要去开始加载后面的requst
        func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            
            // 判断如果不是回调页开头，就去加载
            if let u = request.url {
                let urlString = u.absoluteString
                // 要判断该string是否以回调页开头
                if !urlString.hasPrefix(WB_REDIRECT_URI) {
                    return true
                }
            }
            
            // 如果代码走到这个地方，就代表是回调页
            // 取到url中的查询字符串
            if let query = request.url?.query {
                // 从查询字符串里面截取code
                let code = query.substring(from: "code=".endIndex)
                print(code)
                // 去获取accessToken
                // loadAccessToken(code: code)
                HMUserAccountViewModel.sharedModel.loadAccessToken(code: code, completion: { (isSuccess) in
                    if isSuccess {
                        // 登录成功的话，需要在这个地方切换界面、
                        print("切换界面")
                        self.dismiss(animated: false, completion: {
                            // 切换到欢迎页去
                            NotificationCenter.default.post(name: NSNotification.Name(HMChangeRootVCNotification), object: self)
                        })
                        
                    }else{
                        print("登录失败")
                    }
                })
            }
            
            return false;
        }
        
        // 开始加载的时候
        func webViewDidStartLoad(_ webView: UIWebView) {
            // 显示指示器
            SVProgressHUD.show()
        }
        
        // 结束加载的时候
        func webViewDidFinishLoad(_ webView: UIWebView) {
            // 取消指示器
            SVProgressHUD.dismiss()
        }
        
        // 加载失败的时候
        func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
            SVProgressHUD.dismiss()
        }
        
        // MARK: - 懒加载控件
        
        private lazy var webView: UIWebView = {
            let webView = UIWebView()
            // 设置代理
            webView.delegate = self
            return webView
        }()

}
